﻿// STYLING AND FORMS UI
(function ($) {

    /*
    * charCounter ADAPTED from jqEasyCharCounter plugin, DRASTICALLY altered/gutted
    * Version: 1.0 (05/07/2010) No license. Use it however you want. Just keep this notice included.
    */
    $.fn.extend({
        charCounter: function (givenOptions) {
            return this.each(function () {
                var $this = $(this),
                options = $.extend({ maxChars: 100, hint: '&nbsp;' }, givenOptions);
                if ($this.attr("counter-attached") == "attached" || options.maxChars <= 0)
                    return;
                $this.attr("counter-attached", "attached");

                // create counter element(s)
                var container = $("<div><div class='field-hint'>&nbsp;</div><div class='field-counter'>&nbsp;</div><div style='clear:both; padding:2px;' /></div>");
                container.css({ 'width': $this.width(), 'opacity': 0 });
                container.find(".field-hint")
                    .css({ 'float': 'left' })
                    .html(options.hint);
                var counter = container.find(".field-counter");
                counter.css({ 'float': 'right' });
                container.insertAfter($this);

                // bind events to this element
                $this
				.bind('keydown keyup keypress', doCount)
				.bind('focus paste', function () { setTimeout(doCount, 10); })
				.bind('blur', function () { container.stop().fadeTo('fast', 0); return false; });

                function doCount() {
                    if ($this.val().length >= options.maxChars)
                        counter.attr("class", "field-counter-error");
                    else
                        counter.attr("class", "field-counter");
                    counter.html($this.val().length + " / " + options.maxChars);
                    container.stop().fadeTo('fast', 1);
                };
            });
        }
    });

    /* Initialize UI within the specified root element or document if none specified*/
    function InitUI(root) {

        // get the root jquery element to init
        var thisRoot;
        if (root) { thisRoot = $(root); }
        else { thisRoot = $(document); }

        // trim text to preview length
        thisRoot.find("[previewlength]").each(function () {
            var pl = parseInt($(this).attr("previewlength"));
            if (!isNaN(pl)) {
                if ($(this).text().length > pl) {
                    $(this).attr("title", $(this).text());

                    var ratio = $(this).html().length / $(this).text().length;
                    var htm = $(this).html().substr(0, pl * ratio - 3) + "..."

                    if (htm.lastIndexOf("<") > htm.lastIndexOf(">"))
                        htm = htm.substr(0, htm.lastIndexOf("<"));

                    if (htm.lastIndexOf("<em>") > htm.lastIndexOf("</em>"))
                        htm = htm + "</em>";

                    if (htm.lastIndexOf("<strong>") > htm.lastIndexOf("</strong>"))
                        htm = htm + "</strong>";

                    $(this).html(htm);
                }
            }
        });

        // format dates
        thisRoot.find(".datetime").each(function () {
            try {
                var dt = new Date($(this).text());
                var now = new Date();
                var offset = now.getTimezoneOffset();
                //alert(dt);
                dt = new Date(dt - offset * 60 * 1000);
                //alert(dt);
                var age = (now - dt) / (1000 * 60);

                function pad0(num, len) {
                    var str = "" + num;
                    while (str.length < len)
                        str = "0" + str;
                    return str;
                }

                var M = dt.getMonth() + 1;
                var d = dt.getDate();
                var H = dt.getHours();
                var h = (H == 0 ? 12 : (H > 12 ? H - 12 : H));
                var m = dt.getMinutes();
                var fmt =
                {
                    yyyy: dt.getFullYear(),
                    MM: pad0(M, 2),
                    dd: pad0(d, 2),
                    HH: pad0(H, 2),
                    hh: pad0(h, 2),
                    mm: pad0(m, 2),
                    M: M,
                    d: d,
                    H: H,
                    h: h,
                    m: m,
                    tt: (H > 11 ? "PM" : "AM"),
                    t: (H > 11 ? "P" : "A")
                };

                var format = "M/d/yyyy h:mm tt";
                if (age < 1) {
                    format = "now"
                } else if (age < 2) {
                    format = "1 minute ago"
                } else if (age < 60) {
                    format = Math.floor(age) + " minutes ago"
                } else {
                    $.each(fmt, function (key, value) {
                        format = format.replace(key, value);
                    });
                }
                $(this).text(format);
            } catch (e) { }
        });

        // register char counters
        thisRoot.find("[data-val-length-max]").each(function () {
            var max = $(this).attr("data-val-length-max");
            $(this).charCounter({
                'maxChars': max,
                "hint": (max > 256 ? "<small>Hints: <strong>*strong*</strong>, <em>_emphasis_</em>, () bullet item</small>" : "&nbsp;")
            });
        });

        // forward/disable enter keypress
        //thisRoot.find(".claim-box form").submit(function () {
        //    return false;
        //});
        thisRoot.find(".editor-field input[type='text']").keypress(function (e) {
            if (e.keyCode == 13) {
                return false;
            }
        });


        // register edit links
        thisRoot.find(".edit-button").unbind("click");
        thisRoot.find(".edit-button").click(function () {
            var loadAction = $(this).attr("load-action");
            var postAction = $(this).attr("post-action");
            var thisContainer = $(this).closest(".edit-container");
            var container = thisContainer
            var loadContainer = $(this).attr("load-container");
            var loadContainerNone = false;
            if (loadContainer) {
                if (loadContainer == "none") {
                    loadContainerNone = true;
                } else if (loadContainer == "self") {
                } else {
                    container = $("<div />").attr("class", "edit-container");
                    $(this).closest(".claim-list").find("." + loadContainer).append(container);
                }
            }

            var loadDeletesThis = $(this).is("[load-deletes-this]");

            function exitEmptyPage() {
                var countExistingActions = 0;
                $(".edit-button").each(function () {
                    if ($(this).closest(".claim-box-new").length == 0)
                        countExistingActions++;
                });
                if (countExistingActions == 0 && $(".view-header a").length > 0)
                    window.location.href = $(".view-header a:last").attr("href");
            }

            if (loadAction) {
                container.load(loadAction, function (responseText, textStatus) {
                    if (textStatus != "success") {
                        alert("An error occurred: " + textStatus)
                    } else {
                        InitUI(container);
                        var form = container.find("form:first");
                        $.validator.unobtrusive.parse(form);
                        if (loadContainerNone)
                            container.remove();
                        if (loadDeletesThis)
                            thisContainer.remove();
                    }
                    exitEmptyPage();
                });
            } else if (postAction) {
                var form = thisContainer.find("form:first");
                if (!form.validate().form()) {
                    return false;
                }
                //alert(postAction + ": " + form.serialize());
                $.post(postAction, form.serialize(), function (responseText, textStatus) {
                    if (textStatus != "success") {
                        alert("An error occurred: " + textStatus)
                    } else {
                        container.html(responseText);
                        InitUI(container);
                        $.validator.unobtrusive.parse(form);
                        if (loadContainerNone)
                            container.remove();
                        if (loadDeletesThis)
                            thisContainer.remove();
                    }
                    exitEmptyPage();
                });
            }
        });



        // next?

    }

    // Call when page loads
    InitUI();


    $.setCookie = function (name, value, exdays) {
        var exdate = new Date();
        exdate.setDate(exdate.getDate() + exdays);
        var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString()) + ";path=/";
        document.cookie = name + "=" + c_value;
    }

    $.getCookie = function (name) {
        var i, x, y, ARRcookies = document.cookie.split(";");
        for (i = 0; i < ARRcookies.length; i++) {
            x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
            y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
            x = x.replace(/^\s+|\s+$/g, "");
            if (x == name) {
                return unescape(y);
            }
        }
    }

    $.deleteCookie = function (name) {
        $.setCookie(name, "", -1);
    }

} (jQuery));
